package cn.hznc.controller.service.process.logic;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.domain.entity.ProcessCraftEntity;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工艺逻辑层
 *
 * @Author Administrator
 * @Date 2023/3/16 9:03
 */
public class ProcessCraftLogic {
    private final ProcessCraftDo processCraftDo;

    private final List<ProcessCraftEntity> originProcessCraftList;

    private final List<ProcessCraftEntity> updateProcessCraftList;

    public ProcessCraftLogic(List<ProcessCraftEntity> originProcessCraftList, List<ProcessCraftEntity> updateProcessCraftList) {
        this.originProcessCraftList = originProcessCraftList;
        this.updateProcessCraftList = updateProcessCraftList;
        this.processCraftDo=new ProcessCraftDo();
    }

    /**
     * 获取处理后的业务模型
     *
     * @return subProgramDo
     */
    public ProcessCraftDo getProcessCraftDo() {
        return processCraftDo;
    }

    /**
     * 分离增删改数据
     */
    public void buildProcessCraftDo(){
        if (CollectionUtil.isEmpty(originProcessCraftList)){
            processCraftDo.addCreateElement(updateProcessCraftList);
            return;
        }
        if (CollectionUtil.isEmpty(updateProcessCraftList)){
            processCraftDo.addDeleteElement(originProcessCraftList);
            return;
        }
        // 比对id判断，对删除，修改，新增
        List<Integer> ids = originProcessCraftList.stream().map(ProcessCraftEntity::getId).collect(Collectors.toList());
        List<Integer> updateIds = updateProcessCraftList.stream().filter(updateProcessCraft-> ObjectUtil.isNotNull(updateProcessCraft.getId())).map(ProcessCraftEntity::getId).collect(Collectors.toList());
        for (ProcessCraftEntity processCraftEntity : updateProcessCraftList) {
            // 添加修改元素
            if (ids.contains(processCraftEntity.getId())) {
                processCraftDo.addUpdateElement(processCraftEntity);
            }
            // 添加新增元素
            if (ObjectUtils.isEmpty(processCraftEntity.getId())){
                processCraftDo.addCreateElement(processCraftEntity);
            }
        }
        for (ProcessCraftEntity processCraftEntity : originProcessCraftList) {
            // 添加删除元素
            if (!updateIds.contains(processCraftEntity.getId())){
                processCraftDo.addDeleteElement(processCraftEntity);
            }
        }
    }
}
